package com.example.loop.controller;

import com.example.loop.task.CronTask;
import com.example.loop.task.LoopTask;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.Executors;

/**
 * @author wl
 * @date 2022/3/22
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private CronTask scheduleTask;

    @Resource
    private LoopTask loopTask;

    @Resource
    private RedissonClient redissonClient;

    @GetMapping("/updateCron")
    public String updateCron(@ApiParam(value = "触发定时任务的cron表达式", example = "0/5 * * * * ?") String cron) {
        log.info("new cron :{}", cron);
        scheduleTask.setCron(cron);
        return "ok";
    }


    @GetMapping("/updateTimer")
    public String updateTimer(@ApiParam(value = "触发定时任务的毫秒数",example = "5000") Long timer) {
        log.info("new timer :{}", timer);
        loopTask.setTimer(timer);
        return "ok";
    }


    @ApiOperation("测试redis的多线程同步工具")
    @GetMapping("/test/rcount")
    public String testRCountDownlatch() {

        // 创建一个 RCountDownLatch
        RCountDownLatch rCountDownlatch = redissonClient.getCountDownLatch("testRCountDownlatch");

        // 设置门栓需要扳几下才能打开
        rCountDownlatch.trySetCount(1);

        System.out.println(new Date());

        // 开一个线程countdown一下
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                rCountDownlatch.countDown();
            }
        });

        try {
            rCountDownlatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return "fail" + e.getMessage();
        }

        System.out.println(new Date());

        return "success";
    }
}